//
//  NGNotPostedLocationsViewController.m
//  NetMobileLocation
//
//  Created by Mehmet Sinan Şahin on 1/22/12.
//  Copyright (c) 2012 netgis. All rights reserved.
//

#import "NGNotPostedLocationsViewController.h"
#import "NGDBHelper.h"
#import "NGLocation.h"
#import "NGUtility.h"
#import "NSDate+Extensions.h"
#import "NGAppDelegate.h"
#import "MainRow.h"

@implementation NGNotPostedLocationsViewController


@synthesize notPostedLocationTableView;
@synthesize toLocationsButton;
@synthesize navItem;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = TTLocalizedString(@"Not Posted Locs", @"");
        self.tabBarItem.image = [UIImage imageNamed:@"third"];
        
        UIButton* backButton = [UIButton buttonWithType:101];
        [backButton setTitle:TTLocalizedString(@"Locations", @"") forState:UIControlStateNormal];        
        [backButton addTarget:self
                       action:@selector(toLocations:)
             forControlEvents:UIControlEventTouchUpInside];
        toLocationsButton = [[UIBarButtonItem alloc] initWithCustomView: backButton];        
        
    }
    return self;
}

-(IBAction)toLocations:(id)sender {
    [self.tabBarController setSelectedIndex:0];
    NGAppDelegate *appDelegate = (NGAppDelegate *) [[UIApplication sharedApplication] delegate];
    [appDelegate makeTabBarHidden:FALSE]; 
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - button actions

- (IBAction)showUnsentLocationsSize:(id)sender {
    NGDBHelper *db = [NGDBHelper openDatabase];
    long size = [db howManyLocations: NGLOC_FORLOG];
    
    NSString *message = [[NSString alloc] initWithFormat:@"%d", size];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Gönderilmeyen Sayısı" 
                                                    message:message 
                                                   delegate:nil 
                                          cancelButtonTitle:@"Tamam"
                                          otherButtonTitles:nil];
    [alert show];
    [message release];
    [alert release];    
}

- (IBAction)clear:(id)sender {
    
    UIAlertView *alert = [[UIAlertView alloc] 
                          initWithTitle: TTLocalizedString(@"DeleteAllLocationsTitle", @"")
                          message: TTLocalizedString(@"DeleteAllLocations", @"")
                          delegate: self
                          cancelButtonTitle: TTLocalizedString(@"Cancel", @"")
                          otherButtonTitles: TTLocalizedString(@"Delete", @""), nil];
    [alert show];
    [alert release];
}

// Called when delete all messages button is touched
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    switch (buttonIndex) {          
        case 1: {
            NGDBHelper *db = [NGDBHelper openDatabase];
            [db deleteLocations:NGLOC_UNSENT];
            [self refresh:nil];
        } break;
    }
}

- (IBAction)refresh:(id)sender {
    
    @synchronized(self) {
        if (locations != nil) {
            [locations removeAllObjects];
            [locations release];
        }
        locations = [[NGDBHelper openDatabase] listUnsentLocations]; 
        [self.notPostedLocationTableView reloadData];
    }  
    
}

- (IBAction)send:(id)sender {
    [[NGAppDelegate getApp] sendUnsentLocationToServer:TRUE];
}

- (IBAction)insertTestLocation:(id)sender {
	NGLocation *location = [[[NGLocation alloc] init] autorelease];
	location.lat = 39.91378465;
	location.lon = 32.85948565;
	location.speed = @"0.534";
	location.status = 1;
	location.tarihSaat = [NSDate date];
	location.deviceCode = [NGUtility getDeviceId];
    
    NGDBHelper *db = [NGDBHelper openDatabase];
    [db insertLocationForUnsent:location];
}

#pragma mark - table delegations

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Number of rows
    return [locations count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"NotPostedLocation";
    NGLocation *loc = (NGLocation *)[locations objectAtIndex:indexPath.row];
    return [MainRow createCell:tableView cellIdentifier:cellIdentifier location:loc];  
}

#pragma mark - View lifecycle

- (void)viewWillAppear:(BOOL)animated {
    [self refresh:nil];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.notPostedLocationTableView.delegate = self;
    self.notPostedLocationTableView.dataSource = self;
    self.notPostedLocationTableView.backgroundColor =  [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]];
    [navItem setLeftBarButtonItem:toLocationsButton animated:FALSE];
    [navItem setTitle:TTLocalizedString(@"Not Posted Locs", @"")];

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void) dealloc {
    [notPostedLocationTableView release];
    [toLocationsButton release];
    [navItem release];
    if (locations != nil) [locations release];
    [super dealloc];
}


@end
